package top.buluoluo.ordersservice.enums;

import lombok.Getter;

@Getter
public enum OrderStatus {
    CREATED("已创建", 1),
    PAID("已支付", 2),
    SHIPPED("已发货", 3),
    COMPLETED("已完成", 4),
    CANCELLED("已取消", 0),
    REFUNDED("已退款", 0);

    private final String description;
    private final int priority;

    OrderStatus(String description, int priority) {
        this.description = description;
        this.priority = priority;
    }

    // 业务逻辑方法
    public boolean canBeCancelled() {
        return this == CREATED || this == PAID;
    }

    public boolean isFinal() {
        return this == COMPLETED || this == CANCELLED || this == REFUNDED;
    }

    // 转换方法
    public static OrderStatus fromValue(String value) {
        for (OrderStatus status : values()) {
            if (status.name().equalsIgnoreCase(value)) {
                return status;
            }
        }
        throw new IllegalArgumentException("未知订单状态: " + value);
    }

    /**
     * 状态转换方法
     * @return 新状态
     * @throws IllegalStateException 如果转换无效
     */
    public OrderStatus transitionTo(OrderStatus newStatus) {
        if (!isValidTransition(newStatus)) {
            throw new IllegalStateException(
                    String.format("无法从 %s 转换到 %s", this, newStatus)
            );
        }
        return newStatus;
    }

    private boolean isValidTransition(OrderStatus newStatus) {
        // 实现状态转换规则
        switch (this) {
            case CREATED:
                return newStatus == PAID || newStatus == CANCELLED;
            case PAID:
                return newStatus == SHIPPED || newStatus == REFUNDED;
            case SHIPPED:
                return newStatus == COMPLETED || newStatus == REFUNDED;
            default:
                return false; // 终态不允许转换
        }
    }
}